import React, { useState, useMemo } from "react";

/*
  ! useCallback和useMemo的区别
  它们都有缓存
  useCallback缓存的是函数
  useMemo缓存的是函数的返回值

  ! useCallback和useMemo是否可以相互转换用
  useCallback是可以改写成useMemo的，函数里面返回函数
  useMemo是不能改成useCallback的
*/

const App = () => {
  const [count, setCount] = useState(1);
  const [num, setNum] = useState(10);
  const [list] = useState([1, 2, 3, 4, 5, 6, 7]);

  // useMemo的语法和useCallback一摸一样
  // useMemo就是计算属性
  const fn = useMemo(() => {
    console.log("fn函数执行了");
    let sum = 0;
    for (let i = 0; i < count * 1000; i++) {
      sum += i;
    }
    return sum;
  }, [count]);

  const doubleCount = useMemo(() => {
    return count * 2;
  }, [count]);

  const oddList = useMemo(() => {
    return list.filter((item) => item % 2);
  }, [list]);

  return (
    <>
      <h2>useMemo</h2>
      <p>
        count: {count} -{" "}
        <button onClick={() => setCount((v) => v + 1)}>count++</button>
      </p>
      <p>
        num: {num} -{" "}
        <button onClick={() => setNum((v) => v + 1)}>count++</button>
      </p>

      <p>sum: {fn}</p>
      <p>doubleCount: {doubleCount}</p>
      <ul>
        {oddList.map((item) => (
          <li key={item}>{item}</li>
        ))}
      </ul>
    </>
  );
};

export default App;
